<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\Area;
use App\Models\Admin\Express;
use App\Models\Admin\Goods;
use App\Models\Admin\GoodsRepertoryLog;
use App\Models\Admin\GoodsStore;
use App\Models\Admin\StockOrder;
use App\Models\Admin\StockOrderGoods;
use App\Models\Admin\Store;
use App\Models\Admin\StoreOrder;
use App\Models\Admin\StoreOrderGoods;
use App\Tools\PrPdf;
use App\Tools\Prstatic;
use App\Tools\Texcel;
use Illuminate\Support\Facades\DB;

class StockOrderController extends BaseController
{
    /**
     * 入库单查询
     */
    public function enterOrderList()
    {
        $params = $this->requestArr;
        $params['type'] = 2;
        if ($params['export_excel'] == 1) {
            $list = StockOrder::getPageList($params, 0);
            $title = '库存管理-入库订单';
            $titleArr = ['入库单号', '入库状态', '入库总数', '操作人', '入库备注', '入库时间'];
            $dataArr = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['order_sn'] = $item['order_sn'];
                $dataArr[$k]['status_name'] = $item['status_name'];
                $dataArr[$k]['total_number'] = $item['total_number'];
                $dataArr[$k]['update_user'] = $item['update_user'];
                $dataArr[$k]['remark'] = $item['remark'];
                $dataArr[$k]['store_product_batch'] = $item['store_product_batch'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }

        $list = StockOrder::getPageList($params, $limit = 15);
        if (!empty($params['order_sn'])) {
            $list->appends(['order_sn' => $params['order_sn']])->render();
        }
        if (!empty($params['store_id'])) {
            $list->appends(['store_id' => $params['store_id']])->render();
        }
        if (!empty($params['start_time'])) {
            $list->appends(['start_time' => $params['start_time']])->render();
        }
        if (!empty($params['end_time'])) {
            $list->appends(['end_time' => $params['end_time']])->render();
        }

        $info['data'] = $list;
        return view('admin/stockOrder/enterOrderList', $info);
    }

    /**
     * 添加入货单
     */
    public function enterOrderAdd()
    {
        $params = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            if (!$params['goods']) {
                errorMsg('添加商品');
            }
            $params['create_user'] = $this->userArr['user_name'];
            // 批次号没用 先设置成 -------
            $params['store_product_batch'] = '-----';
            StockOrder::enterInfoByAdmin($params);
            successMsg();
        } else {
            $info['goodsList'] = Goods::getRepertoryList();
            $info['goodsListStr'] = json_encode($info['goodsList'], JSON_UNESCAPED_UNICODE);
            $info['stockStatus'] = Prstatic::$stockStatus;
            $info['data'] = ['order_sn' => pdStoreSn('KCR')];
            return view('admin/stockOrder/enterOrderAdd', $info);
        }
    }

    /**
     * 修改订单信息
     */
    public function enterOrderEdit()
    {
        $params = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            if ($params['id']) {
                successMsg();
            }
            errorMsg();
        } else {
            if ($params['id']) {
                $info = StockOrder::getInfoById($params['id']);
                $info['goods_list'] = StockOrderGoods::getListByOid($params['id']);
            }
            $stockStatus = Prstatic::$stockStatus;
            return view('admin/stockOrder/enterOrderEdit', ['data' => $info, 'orderStatus' => $stockStatus]);
        }
    }


    /**
     * 出库单查询
     */
    public function outOrderList()
    {
        $params = $this->requestArr;
        $params['type'] = 1;
        if ($params['export_excel'] == 1) {
            $list = StockOrder::getPageList($params, 0);
            $title = '库存管理-出库订单';
            $titleArr = ['出库单号','快递单号', '出库状态', '代理商', '出库数量', '操作人', '出库备注', '出库时间', '出库商品批次'];
            $dataArr = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['order_sn'] = $item['order_sn'];
                $dataArr[$k]['tracking_number'] = $item['tracking_number'];
                $dataArr[$k]['status_name'] = $item['status_name'];
                $dataArr[$k]['store_name'] = $item['store_name'];
                $dataArr[$k]['total_number'] = $item['total_number'];
                $dataArr[$k]['update_user'] = $item['update_user'];
                $dataArr[$k]['remark'] = $item['remark'];
                $dataArr[$k]['created_at'] = $item['created_at'];
                $dataArr[$k]['store_product_batch'] = $item['store_product_batch'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }
        $list = StockOrder::getPageList($params, $limit = 15);
        if (!empty($params['order_sn'])) {
            $list->appends(['order_sn' => $params['order_sn']])->render();
        }
        if (!empty($params['tracking_number'])) {
            $list->appends(['tracking_number' => $params['tracking_number']])->render();
        }
        if (!empty($params['store_id'])) {
            $list->appends(['store_id' => $params['store_id']])->render();
        }
        if (!empty($params['start_time'])) {
            $list->appends(['start_time' => $params['start_time']])->render();
        }
        if (!empty($params['end_time'])) {
            $list->appends(['end_time' => $params['end_time']])->render();
        }
        if (!empty($params['store_product_batch'])) {
            $list->appends(['store_product_batch' => $params['store_product_batch']])->render();
        }
        $info['storeList'] = Store::getBaseList();
        $info['data'] = $list;
        return view('admin/stockOrder/outOrderList', $info);
    }

    // 订单PDF打印
    public function orderPdf()
    {
        $params = $this->requestArr;
        if ($params['id']) {
            $info = StockOrder::getInfoById($params['id']);
            $goodsList = StockOrderGoods::getListByOid($params['id']);
            $total = [];
            foreach ($goodsList as $item) {
                $total['num'] += $item['goods_number'];
                if ($item['is_give'] == 0) {
                    $total['goods_price_yu'] += $item['goods_price_yu'];
                    $total['goods_price_zn'] += $item['goods_price_yu'] * $item['goods_number'];
                }
            }
            $storeInfo = Store::getInfoById($info['store_id']);
            $info['subsidiary'] = $storeInfo['subsidiary'] ?? "亿恩鑫（上海）生物科技有限公司";
            $html = view('admin/order/orderPdf', ['data' => $info, 'storeInfo' => $storeInfo, 'goodsList' => $goodsList, 'total' => $total]);
            $pdf = new PrPdf();
            return $pdf->makePdfByHtml($storeInfo['subsidiary'], $info['order_sn'], $html, 1);
        }
        errorMsg();
    }


    /**
     * 修改订单信息
     */
    public function outOrderEdit()
    {
        $params = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            if ($params['id']) {
                successMsg();
            }
            errorMsg();
        } else {
            if ($params['id']) {
                $info = StockOrder::getInfoById($params['id']);
                $info['goods_list'] = StockOrderGoods::getListByOid($params['id']);
                $storeInfo = Store::getInfoById($info['store_id']);
            }
            $stockStatus = Prstatic::$stockStatus;
            return view('admin/stockOrder/outOrderEdit', ['data' => $info, 'storeInfo' => $storeInfo, 'orderStatus' => $stockStatus]);
        }
    }

    /**
     * 处理组合商品库存扣减
     * @param int $goodsId 商品ID
     * @param int $quantity 数量
     * @param string $orderSn 订单编号
     * @throws \Exception
     */
    private function handleGroupGoodsStock($goodsId, $quantity, $orderSn = '')
    {
        DB::beginTransaction();
        try {
            // 获取组合商品信息
            $goods = Goods::find($goodsId);
            if (!$goods || $goods->is_group != 1 || empty($goods->goods_group)) {
                throw new \Exception('非组合商品或商品不存在');
            }

            // 获取子商品列表
            $subGoodsIds = explode(',', $goods->goods_group);
            
            // 检查并扣减子商品库存
            foreach ($subGoodsIds as $subGoodsId) {
                $subGoods = Goods::find($subGoodsId);
                if (!$subGoods) {
                    throw new \Exception("子商品[ID:{$subGoodsId}]不存在");
                }

                // 检查子商品库存
                if ($subGoods->goods_sale_num < $quantity) {
                    throw new \Exception("商品[{$subGoods->goods_name}]库存不足");
                }

                // 扣减子商品库存
                $subGoods->decrement('goods_sale_num', $quantity);
                $subGoods->decrement('goods_total_num', $quantity);

                // 记录库存变动日志
                GoodsRepertoryLog::create([
                    'order_sn' => $orderSn,
                    'goods_id' => $subGoodsId,
                    'goods_num' => -$quantity,
                    'goods_after_num' => $subGoods->goods_sale_num - $quantity,
                    'type' => 1, // 出库
                    'remark' => "组合商品[{$goods->goods_name}]出库",
                    'created_at' => time(),
                    'create_user' => $this->userArr['user_name']
                ]);
            }

            // 扣减组合商品库存
            $goods->decrement('goods_sale_num', $quantity);
            $goods->decrement('goods_total_num', $quantity);

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    /**
     * 添加出货单
     */
    public function outOrderAdd()
    {
        $params = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            if (!$params['order_name']) {
                errorMsg('请填写收货人');
            }
            if (!$params['order_mobile']) {
                errorMsg('请填写收货人电话');
            }
            if (!$params['order_province'] || !$params['order_city'] || !$params['order_area'] || !$params['order_address']) {
                errorMsg('请填写收货人地址');
            }
            if (!$params['express_id']) {
                errorMsg('请选择快递');
            }
            if (!$params['goods']) {
                errorMsg('请添加商品');
            }

            DB::beginTransaction();
            try {
                $params['create_user'] = $this->userArr['user_name'];
                
                // 处理商品库存
                foreach ($params['goods'] as $item) {
                    $goods = Goods::find($item['goods_id']);
                    if (!$goods) {
                        throw new \Exception('商品不存在');
                    }

                    if ($goods->is_group == 1) {
                        // 组合商品库存处理
                        $this->handleGroupGoodsStock($goods->id, $item['goods_number'], $params['order_sn']);
                    } else {
                        // 普通商品库存处理
                        if ($goods->goods_sale_num < $item['goods_number']) {
                            throw new \Exception("商品[{$goods->goods_name}]库存不足");
                        }
                        
                        $goods->decrement('goods_sale_num', $item['goods_number']);
                        $goods->decrement('goods_total_num', $item['goods_number']);
                        
                        // 记录库存变动
                        GoodsRepertoryLog::create([
                            'order_sn' => $params['order_sn'],
                            'goods_id' => $goods->id,
                            'goods_num' => -$item['goods_number'],
                            'goods_after_num' => $goods->goods_sale_num - $item['goods_number'],
                            'type' => 1,
                            'remark' => '普通商品出库',
                            'created_at' => time(),
                            'create_user' => $this->userArr['user_name']
                        ]);
                    }
                }

                // 创建出库单
                StockOrder::outInfoByAdmin($params);

                DB::commit();
                successMsg();
            } catch (\Exception $e) {
                DB::rollBack();
                errorMsg($e->getMessage());
            }
        } else {
            $info['storeList'] = Store::getBaseList();
            $info['expressCompany'] = Express::getAllList();
            $info['goodsList'] = Goods::getRepertoryList();
            $info['goodsListStr'] = json_encode($info['goodsList'], JSON_UNESCAPED_UNICODE);
            $info['stockStatus'] = Prstatic::$stockStatus;
            $info['data'] = ['order_sn' => pdStoreSn('KCC')];
            return view('admin/stockOrder/outOrderAdd', $info);
        }
    }

    /**
     * 商户商品
     */
    public function outOrderGoods()
    {
        $params = $this->requestArr;
        if ($params['store_id']) {
            if ($params['goods_id']) {
                $goodsList = GoodsStore::getInfoBySid($params['store_id'], $params['goods_id']);
            } else {
                $goodsList = GoodsStore::getRepertoryList($params['store_id']);
            }
            successMsg($goodsList);
        } else {
            $goodsList = Goods::getRepertoryList();
            successMsg($goodsList);
        }
        errorMsg();
    }

    /**
     * 库存列表
     */
    public function repertoryList()
    {
        $params = $this->requestArr;
        if ($params['export_excel'] == 1) {
            $list = Goods::getPageRepertoryList($params, 0);
            $title = '库存管理-库存列表';
            $titleArr = ['商品分类', '商品编号', '商品名称', '商品类型', '商品单价', '当前库存', '当前可售库存'];
            $dataArr = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['cate_name'] = $item['cate_name'];
                $dataArr[$k]['goods_sn'] = $item['goods_sn'];
                $dataArr[$k]['goods_name'] = $item['goods_name'];
                $dataArr[$k]['goods_type_name'] = $item['goods_type_name'];
                $dataArr[$k]['goods_price'] = $item['goods_price'];
                $dataArr[$k]['goods_total_num'] = $item['goods_total_num'];
                $dataArr[$k]['goods_sale_num'] = $item->is_group == 1 ? $item->real_stock : $item['goods_sale_num'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }
        $list = Goods::getPageRepertoryList($params, $limit = 15);
        if (!empty($params['name'])) {
            $list->appends(['name' => $params['name']])->render();
        }
        if (!empty($params['good_sn'])) {
            $list->appends(['good_sn' => $params['good_sn']])->render();
        }
        return view('admin/stockOrder/repertoryList', ['data' => $list]);
    }

    // 单品入库
    public function repertoryOneEnter()
    {
        $params = $this->requestArr;
        if ($params['goods_id']) {
            $info['goods'] = Goods::getInfoById($params['goods_id']);
        }
        $info['data'] = ['order_sn' => pdStoreSn('KCR')];
        return view('admin/stockOrder/repertoryOneEnter', $info);
    }

    // 单品出库
    public function repertoryOneOut()
    {
        $params = $this->requestArr;
        if ($params['goods_id']) {
            $info['goods'] = Goods::getInfoById($params['goods_id']);
        }
//        StockOrder::getBaseStockOrderList()
        $info['storeList'] = Store::getBaseList();//获取列表
        $info['expressCompany'] = Express::getAllList();
//        StockOrder::where();
        $info['stockStatus'] = Prstatic::$stockStatus;
        $info['data'] = ['order_sn' => pdStoreSn('KCC')];
        return view('admin/stockOrder/repertoryOneOut', $info);
    }


    /**
     * 库存变动记录
     */
    public function repertoryLogList()
    {
        $params = $this->requestArr;
        if ($params['export_excel'] == 1) {
            $list = GoodsRepertoryLog::getPageList($params, 0);
            $title = '库存管理-库存变动记录';
            $titleArr = ['商品分类', '商品编号', '商品名称', '出入库数量', '出入库类型', '相关代理商', '操作人', '操作时间', '出入库单号'];
            $dataArr = [];
            foreach ($list as $k => $item) {
                $dataArr[$k]['cate_name'] = $item['cate_name'];
                $dataArr[$k]['goods_sn'] = $item['goods_sn'];
                $dataArr[$k]['goods_name'] = $item['goods_name'];
                $dataArr[$k]['goods_num'] = $item['goods_num'];
                $dataArr[$k]['type_name'] = $item['type_name'];
                $dataArr[$k]['store_name'] = $item['store_name'];
                $dataArr[$k]['create_user'] = $item['create_user'];
                $dataArr[$k]['created_at'] = $item['created_at'];
                $dataArr[$k]['order_sn'] = $item['order_sn'];
            }
            if (empty($dataArr)) {
                view()->share('layout_message', '暂无导出数据');
            } else {
                Texcel::exportExcelHtml($title, $titleArr, $dataArr);
            }
            exit();
        }
        $list = GoodsRepertoryLog::getPageList($params, $limit = 15);
        if (!empty($params['store_id'])) {
            $list->appends(['store_id' => $params['store_id']])->render();
        }
        if (!empty($params['name'])) {
            $list->appends(['name' => $params['name']])->render();
        }
        if (!empty($params['order_sn'])) {
            $list->appends(['order_sn' => $params['order_sn']])->render();
        }
        if (!empty($params['type'])) {
            $list->appends(['type' => $params['type']])->render();
        }
        if (!empty($params['start_time'])) {
            $list->appends(['start_time' => $params['start_time']])->render();
        }
        if (!empty($params['end_time'])) {
            $list->appends(['end_time' => $params['end_time']])->render();
        }
        $info['storeList'] = Store::getBaseList();
        $info['data'] = $list;
        return view('admin/stockOrder/repertoryLogList', $info);
    }

}
